package cn.jsu.oj.dispatchServer.handle.handles;

import cn.jsu.oj.dispatchServer.config.ResourceConfig;
import cn.jsu.oj.dispatchServer.handle.CommandPack;
import cn.jsu.oj.dispatchServer.init.ClientInitVector;
import cn.jsu.oj.dispatchServer.net.DispatchServerHandle;
import cn.jsu.oj.dispatchServer.pojo.CmdInformation;
import cn.jsu.oj.dispatchServer.pojo.StatusCmdResultPack;
import cn.jsu.oj.dispatchServer.utils.LocalUsedInfo;
import cn.jsu.oj.dispatchServer.utils.NetUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;

/**
 * @author ahtonc
 */
@Slf4j
public class GetStateHandle implements Handle {
    private static final int GET_STATE_TYPE = 4;
    private static final String SERVER_IP;
    private static final short SERVER_PORT;

    static {
        SERVER_IP = NetUtil.getHostAddress();
        SERVER_PORT = ResourceConfig.getConfigShort("net.server.port");
    }

    @Override
    public CommandPack<?> handle(CommandPack<?> pack) {
        CmdInformation cmd = (CmdInformation) pack.getData();

        if (cmd.getCmdType() != GET_STATE_TYPE) {
            log.error("GetStateHandle command type is " + cmd.getCmdType());
            return null;
        }

        if (cmd.getIp().equals(SERVER_IP) && cmd.getPort() == SERVER_PORT) {
            StatusCmdResultPack resultPack = new StatusCmdResultPack();
            //设置内容
            resultPack.setIp(SERVER_IP);
            resultPack.setPort(SERVER_PORT);
            resultPack.setDisk(Double.toString(LocalUsedInfo.realDisk()));
            resultPack.setMemory(Double.toString(LocalUsedInfo.memoryUsage()));
            resultPack.setNetWorkStatusIn(Float.toString(LocalUsedInfo.ioUsage()));
            resultPack.setNetWorkStatusOut(Float.toString(LocalUsedInfo.ioUsage()));

            //cpu
            double cpu = 0;
            Map<?, ?> cpuInfo = LocalUsedInfo.cpuinfo();
            for (Object o : cpuInfo.keySet()) {
                cpu += Double.parseDouble(cpuInfo.get(o).toString());
            }
            resultPack.setCpuUserRate(Double.toString(cpu));

            log.debug("GetStateHandle command(server) result: " + resultPack);
            DispatchServerHandle.vectorMap.get(pack.getIpAndPort()).addTask(resultPack);
        } else {
            log.debug("GetStateHandle forward command: " + pack.toString());
            ClientInitVector initVector = DispatchServerHandle.vectorMap.get(cmd.getIp() + cmd.getPort());
            initVector.addTask(pack);
        }

        return null;
    }
}
